package chloroform

import scaladuct._

/**
 * This trait is responsible for injecting context values into cookie properties.
 */
trait InjectingGateway[X] extends ConfigPageGateway[X] {

  def lookupFunction(): LookupFunctions.LookupFunction;

  override def consumeCookie(cookie: AnyRef) = {
    super.consumeCookie(cookie)
//    val lookupFn: LookupFunctions.LookupFunction = lookupFunction()
//
//    if (cookie != Terminal && lookupFn != null) {
//      val cookieBean = CookieBeanFactory(cookie)
//
//      def filterContextReferences(prop: PropertyValue[AnyRef]): Boolean = {
//        prop.refTypeInfo != null && prop.refTypeInfo.name != null &&
//          prop.refTypeInfo.name != "" &&
//          prop.clazz != classOf[String]
//      }
//
//      def inject(prop: PropertyValue[AnyRef]): PropertyValue[AnyRef] = {
//        //val lookupFn: LookupFunctions.LookupFunction = lookupFunction()
//
//        val resultPageFns = lookupFn(prop.refTypeInfo.name)
//        if (resultPageFns.size == 1) {
//          val valuePageFn = resultPageFns(0)
//          //val valuePage = valuePageFn(prop.clazz)
//          val valuePage = valuePageFn(prop.typeInfo.getType)
//          if (valuePage.getCookie == Terminal) {
//            valuePage.consume(valuePage.getCookie) match {
//              case NextPage(page) => error("Consuming terminal yields another page instead of a starter")
//              case NewStarter(starter) => {
//                // Note: the starter should to return a context value that does not have to be explicitly destroyed.
//                val value = starter.newInstance
//
//                prop.update(value.asInstanceOf[AnyRef])
//              }
//            }
//          } else {
//            error("Referenced page " + prop.refTypeInfo.name + " is not fully preconfigured")
//          }
//        } else error("Lookup for '" + prop.refTypeInfo.name + "' returns " + resultPageFns.size + " results. Just one expected." )
//      }
//
//      val updatedProps = cookieBean.props.filter(filterContextReferences).map(inject)
//      if (!updatedProps.isEmpty) {
//        cookieBean.update(updatedProps)
//      }
//
//      super.consumeCookie(cookie)
//
//    } else {
//      if (lookupFn == null)
//        warn("Lookup function is not available for injecting context values")
//
//      super.consumeCookie(cookie)
//    }
//
  }
}